package my.client.controller;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import my.client.model.Vehicle;
import my.client.model.VehicleHistory;
import my.client.service.VehicleHistoryServiceDelegator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;

public class AddVehicleController extends AbstractWizardFormController {

	Logger logger = LoggerFactory.getLogger(getClass());
	
	private CustomDateEditor customDateEditor;
	
	private VehicleHistoryServiceDelegator delegator;
	
	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Date.class, customDateEditor);
		super.initBinder(request, binder);
	}
	
	@Override
	protected ModelAndView processFinish(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		logger.debug("VehicleHistory {}",command);
		Vehicle vehicle = (Vehicle)command;
		delegator.addVehicleHistory(vehicle);
		ModelAndView modelAndView = new ModelAndView("add-vehicle-confirmation");
		modelAndView.addObject("vehicle", vehicle);
		modelAndView.addObject("message","Vehicle history successfully added.");
		return modelAndView;
	}
	
	@Override
	protected ModelAndView processCancel(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		return new ModelAndView("welcome");
	}

	@Override
	protected void onBindAndValidate(HttpServletRequest request,
			Object command, BindException errors, int page) throws Exception {
		Vehicle vehicle = (Vehicle) command;
		if(page == 0 && vehicle.getHistory() == null){
			Set<VehicleHistory> history = new HashSet<VehicleHistory>();
			VehicleHistory vehHistory = new VehicleHistory();
			history.add(vehHistory);
			vehicle.setHistory(history);
		}
		super.onBindAndValidate(request, vehicle, errors, page);
	}
	
	/**
	 * @param customDateEditor the customDateEditor to set
	 */
	public void setCustomDateEditor(CustomDateEditor customDateEditor) {
		this.customDateEditor = customDateEditor;
	}

	/**
	 * @param delegator the delegator to set
	 */
	public void setDelegator(VehicleHistoryServiceDelegator delegator) {
		this.delegator = delegator;
	}

	
}
